package com.lundao.blog.controller;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lundao.common.annotation.Anonymous;
import com.lundao.domain.Comment;
import com.lundao.service.impl.CommentServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import javax.annotation.Resource;
import com.lundao.mapper.CommentMapper;

@Slf4j
@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")   // 本地 dev 跨域
public class AIController {

    @Value("${deepseek.api-key}")
    private String apiKey;

    private static final String DEEPSEEK_URL = "https://api.deepseek.com/v1/chat/completions";

    @Resource
    private CommentServiceImpl commentService;   // 机器人评论落库

    @Resource
    private CommentMapper commentMapper;

    /* ==================== 1. 问答 ==================== */
    @PostMapping("/ask")
    public JSONObject ask(@RequestBody JSONObject req) {
        String question = req.getString("question");
        if (question == null || question.trim().isEmpty()) {
            return new JSONObject().fluentPut("error", "内容不能为空");
        }
        String answer = callDeepSeek(question, 0.7, 500);
        return new JSONObject().fluentPut("answer", answer);
    }

    /* ==================== 2. 摘要 ==================== */
    @PostMapping("/generate-summary")
    public JSONObject generateSummary(@RequestBody JSONObject req) {
        String content = req.getString("content");
        String title   = req.getString("title");
        if (content == null || content.trim().isEmpty()) {
            return new JSONObject().fluentPut("error", "内容不能为空");
        }

        // 去 HTML 并截断
        String plain = content.replaceAll("<[^>]+>", "");
        if (plain.length() > 2000) plain = plain.substring(0, 2000) + "...";

        String prompt = (title != null && !title.trim().isEmpty())
                ? "请为以下博客生成150字以内摘要：\n标题：" + title + "\n内容：" + plain
                : "请为以下博客生成150字以内摘要：\n" + plain;

        String summary = callDeepSeek(prompt, 0.3, 200)
                .replaceAll("^(摘要|总结|概要)[：:]?", "");
        return new JSONObject()
                .fluentPut("code", 200)
                .fluentPut("msg", "成功")
                .fluentPut("data", new JSONObject().fluentPut("summary", summary));
    }

    /* ==================== 3. 机器人评论 ==================== */
    @Anonymous
    @PostMapping("/robot-comment")
    public JSONObject robotComment(@RequestBody JSONObject req) {
        String blogId = req.getString("blogId");
        String content = req.getString("content");

        log.info("【机器人评论】接收到请求，blogId={}", blogId);

        Comment comment = new Comment();
        comment.setBlogId(blogId);
        comment.setContent(content);
        comment.setUserId(0); // 机器人用户
        comment.setCreateTime(new Date());

        commentMapper.insertComment(comment);
        return new JSONObject().fluentPut("msg", "AI评论成功").fluentPut("code", 200);
    }

    /* ==================== 公共调用 ==================== */
    private String callDeepSeek(String prompt, double temperature, int maxTokens) {
        RestTemplate rest = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        JSONArray messages = new JSONArray();
        messages.add(new JSONObject().fluentPut("role", "user").fluentPut("content", prompt));

        JSONObject body = new JSONObject();
        body.put("model", "deepseek-chat");
        body.put("messages", messages);
        body.put("temperature", temperature);
        body.put("max_tokens", maxTokens);

        HttpEntity<String> entity = new HttpEntity<>(body.toJSONString(), headers);
        String resp = rest.postForObject(DEEPSEEK_URL, entity, String.class);

        return JSONObject.parseObject(resp)
                .getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content")
                .trim();
    }
}